package com.itheima.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.itheima.properties.AliyunOssProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Component
public class AliyunOssUitls {

    @Autowired
    private AliyunOssProperties aliyunOssProperties;

    public String uploadImg(MultipartFile file) throws Exception {
        System.out.println("=================>");
        OSS ossClient = new OSSClientBuilder().build(
                aliyunOssProperties.getEndpoint(),
                aliyunOssProperties.getAccessKeyId(),
                aliyunOssProperties.getAccessKeySecret());
        InputStream inputStream = file.getInputStream();
        String filename = file.getOriginalFilename();   //zhangsan.jpg
        String suffixName = filename.substring(filename.lastIndexOf("."));   //.jpg
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");//adfklusafbj234097fsdklsdfbjksdfhjk
        filename = uuid + suffixName;  //adfklusafbj234097fsdklsdfbjksdfhjk.jpg
        PutObjectRequest putObjectRequest = new PutObjectRequest(aliyunOssProperties.getBucketName(), filename, inputStream);
        putObjectRequest.setProcess("true");

        PutObjectResult result = ossClient.putObject(putObjectRequest);
        if (result.getResponse().getStatusCode() == 200) {
            //https://ybbcqwiu.oss-cn-hangzhou.aliyuncs.com/meinv.jpg
            return "https://" + aliyunOssProperties.getBucketName() + "." + aliyunOssProperties.getEndpoint() + "/" + filename;
        }
        if (ossClient != null) {
            ossClient.shutdown();
        }
        return null;
    }
} 